package com.dgut.smart_house.controller;

import com.dgut.smart_house.domain.User;
import com.dgut.smart_house.enums.ResultCode;
import com.dgut.smart_house.service.DeviceListService;
import com.dgut.smart_house.service.UserService;
import com.dgut.smart_house.util.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/api")
public class LoginApiController {


    @Autowired
    UserService userService;

    @Autowired
    DeviceListService deviceListService;

    /**
     * 登录
     *
     * @param userId
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public RestResult login(@RequestParam("userId") String userId,
                            @RequestParam("password") String password,
                            HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {

            UsernamePasswordToken token = new UsernamePasswordToken(userId, password);
            try {
                subject.login(token);

                HttpSession session = request.getSession();
                session.setAttribute("IdFromUserTable", userService.findByUserId(userId).getId());
                session.setAttribute("userId", token.getUsername());
                log.info("用户-{}-登录了系统", userId);
                return new RestResult(ResultCode.LOGIN_SUCCESS, null);
            } catch (UnknownAccountException e) {
                return new RestResult(ResultCode.UNKNOWN_ACCOUNT, null);
            } catch (IncorrectCredentialsException e) {
                return new RestResult(ResultCode.PASSWORD_ERROR, null);
            }

        }

        return new RestResult(ResultCode.NO_AUTH_FAIL, null);

    }


    /**
     * 注册
     *
     * @param userId
     * @param password
     * @param email
     * @return
     */
    @PostMapping("/register")
    public RestResult register(@RequestParam("userId") String userId,
                               @RequestParam("password") String password,
                               @RequestParam("email") String email
    ) {
        if(userService.findByUserId(userId)!=null){
            return new RestResult(ResultCode.USER_EXIST,null);
        }
        if (userService.createUser(userId, password, email) == 1) {
            log.info("用户-{}-注册了账户", userId);
            return new RestResult(ResultCode.SUCCESS.getCode(), "注册成功", null);
        } else {
            return new RestResult(ResultCode.REGISTER_FAIL, null);
        }
    }


    /**
     * 判断用户名是否已存在
     *
     * @param userId
     * @return
     */
    @PostMapping("/register/if_user_exit")
    public RestResult register(@RequestParam("userId") String userId
    ) {
        if(userService.findByUserId(userId)!=null){
            return new RestResult(ResultCode.USER_EXIST,null);
        }else{
            return new RestResult(ResultCode.SUCCESS.getCode(),"用户名可用",null);
        }
    }


    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping("/signOut")
    public RestResult signOut() {
        Subject subject = SecurityUtils.getSubject();
        log.info("用户-{}-退出登录了", ((User) subject.getPrincipal()).getUserId());
        subject.logout();
        return new RestResult(ResultCode.SUCCESS.getCode(), "退出成功", null);
    }

    @RequestMapping("/nologin")
    public RestResult nologin(){
        return new RestResult(ResultCode.NO_LOGIN,null);
    }


    @RequestMapping("/noAuth")
    public RestResult noAuth(){
        return new RestResult(ResultCode.NO_AUTH_FAIL,null);
    }

}
